#region File Header
//
// DispatcherTimer.cs - Dispatcher Timer
//
// Copyright (C) Javier Valcarce. BSD License
#endregion

#region Using Statements
using System;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
#endregion


namespace Arq
{
    /// <summary>
    /// Simple dispatcher. The task queue is synchronized.
    /// </summary>
    public class DispatcherTimer
    {
        #region Private Members
        Timer              timer;
        Dispatcher         dispatcher;
        DispatcherDelegate task;
        object             arg;
        #endregion

        #region Constructors
        public DispatcherTimer(Dispatcher dispatcher, int dueTime, int period, DispatcherDelegate task)
            : this(dispatcher, dueTime, period, task, null)
        {
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="threadName">Event Queue Processor Thread Name</param>
        /// <param name="background">Put the thread in background</param>
        public DispatcherTimer(Dispatcher dispatcher, int dueTime, int period, 
            DispatcherDelegate task, object arg)
        {
            Debug.Assert(dispatcher != null);
            Debug.Assert(task       != null);
        
            
            this.dispatcher = dispatcher;
            this.timer      = new Timer(Timer_Tick, null, dueTime, period);
            this.task       = task;
            this.arg        = arg;
        }     
        #endregion

        #region Public Methods
        /// <summary>
        /// Changes the start time and the interval between method invocations for a timer, using 
        /// 32-bit signed integers to measure time intervals. 
        /// </summary>
        /// <param name="dueTime">
        /// The amount of time to delay before the invoking the callback method specified when the
        /// Timer was constructed, in milliseconds. Specify Timeout..::.Infinite to prevent the 
        /// timer from restarting. Specify zero (0) to restart the timer immediately.
        /// </param>
        /// <param name="period">
        /// The time interval between invocations of the callback method specified when the Timer 
        /// was constructed, in milliseconds. Specify Timeout..::.Infinite to disable periodic 
        /// signaling.
        /// </param>
        /// <returns>
        /// true if the current instance has not been disposed; otherwise, false.
        /// </returns>
        public bool Change(int dueTime, int period)
        {
            return timer.Change(dueTime, period);
        }

        
        #endregion

        // System.Threading.Timer Event Handler
        private void Timer_Tick(object state)
        {
            // Execute periodically the specified task
            dispatcher.BeginInvoke(task, arg);
        }
    }
}